package api

import (
	restfulspec "github.com/emicklei/go-restful-openapi/v2"
	"github.com/infraboard/mcube/v2/exception"
	"github.com/infraboard/mcube/v2/http/label"
	"github.com/infraboard/mcube/v2/ioc"
	"github.com/infraboard/mcube/v2/ioc/config/gorestful"
	"github.com/infraboard/mcube/v2/ioc/config/log"
	"github.com/rs/zerolog"
	"gitlab.com/go-course-project/go15/devcloud-mini/cmdb/apps/secret"
)

func init() {
	ioc.Api().Registry(&handler{})
}

type handler struct {
	ioc.ObjectImpl

	// 模块子Logger
	log *zerolog.Logger
	svc secret.Service
}

func (h *handler) Name() string {
	return secret.AppName
}

func (h *handler) Init() error {
	tags := []string{"凭证管理"}

	// 对象
	h.log = log.Sub(h.Name())
	h.svc = secret.GetService()

	ws := gorestful.ObjectRouter(h)

	// r.Use()
	// FilterFunction definitions must call ProcessFilter on the FilterChain to pass on the control and eventually call the RouteFunction
	// type FilterFunction func(*Request, *Response, *FilterChain)
	// ws.Filter(func(r1 *restful.Request, r2 *restful.Response, fc *restful.FilterChain) {
	// 	// 如何在中间件里面获取路有条目信息
	// 	//  curl  localhost:8020/api/cmdb/v1/secret
	// 	sr := r1.SelectedRoute()
	// 	md := sr.Metadata()

	// 	h.log.Debug().Msgf("ua: %s", r1.Request.UserAgent())
	// 	h.log.Debug().Msgf("resource: %s", md[label.Resource])
	// 	h.log.Debug().Msgf("action: %s", md[label.Action])
	// 	h.log.Debug().Msgf("method: %s", sr.Method())
	// 	h.log.Debug().Msgf("path: %s", sr.Path())
	// 	h.log.Debug().Msgf("operation: %s", sr.Operation())
	// })

	// 需要做出websocket
	//
	ws.Route(ws.GET("/{id}").To(h.DescribeSecret).
		// 开启审计
		Metadata(label.Audit, label.Enable).
		Metadata(label.Resource, h.Name()).
		Metadata(label.Action, label.Get.Value()).
		// 开启认证
		Metadata(label.Auth, label.Enable).
		Metadata(label.Permission, label.Enable).
		Doc("凭证资源同步").
		Metadata(restfulspec.KeyOpenAPITags, tags))

	// 服务(启动的时候获取本服务的名称), 资源类型, 动作
	ws.Route(ws.GET("").To(h.QuerySecret).
		// 开启审计
		Metadata(label.Audit, label.Enable).
		Metadata(label.Resource, h.Name()).
		Metadata(label.Action, label.List.Value()).
		// 开启认证
		Metadata(label.Auth, label.Enable).
		Metadata(label.Permission, label.Enable).
		// API Doc
		Doc("凭证列表查询").
		Param(ws.PathParameter("page_size", "页大小").DataType("int").Required(false).DefaultValue("20")).
		Param(ws.PathParameter("page_number", "页码").DataType("int").Required(false).DefaultValue("1")).
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Writes(secret.NewSecretSet()).
		Returns(200, "OK", secret.NewSecretSet()).
		Returns(404, "Not Found", exception.ApiException{}))

	// 需要做出websocket
	//
	ws.Route(ws.POST("/{id}/sync").To(h.SyncResource).
		Metadata(label.Audit, label.Enable).
		Metadata(label.Resource, h.Name()).
		Metadata(label.Action, label.List.Value()).
		Doc("凭证资源同步").
		Metadata(restfulspec.KeyOpenAPITags, tags))
	return nil
}
